#include "base.h"
#include "graphics.h"
#include "ex_math.h"

#include "gml.h"
#include "room.h"

namespace gml
{
 //初始化静态变量
 std::list<room*>
 room::all_room;
 //当前房间
 room*room::_room;
 
 //定时器回调
 void roomTimerCB(int32 data)
 {
  room*rm = (room*)data;
  rm->event_step();
 }
 
 //构造函数
 room::room()
 {
  //屏幕宽高
  this->width = SCRW;
  this->height = SCRH;
  
  //速度与背景
  room_speed = 1000/30;
  background = 0xffffffff;
  
  //视野坐标
  view_pos_x = 0;
  view_pos_y = 0;
  
  //开启定时器
  timer = timercreate();
  timerstart(timer,room_speed,
   (int32)this,roomTimerCB,TRUE);
   
  //添加
  all_room.push_back(this);
 }
 
 //析构函数
 room::~room()
 {
  //删除自己
  timerdel(timer);
  all_room.remove(this);
  
  //清空非keep的object
  for(object*obj:object::all_object)
  	if(!obj->keep)
  	delete obj;
  
  printf("room%d ~room()\n",this);
 }
 
 //排序
 bool sortObjDepth(const object&m1,const object&m2)
 {
  return m1.depth<m2.depth;
 }
 
 //创建事件
 void room::event_create()
 {
  printf("room%d create()\n",this);
 }
 
 //步事件
 void room::event_step()
 {
  if(_room!=this)
  	return;
  
  //定时器
  //printf("room step alarm\n");
  for(object*obj:object::all_object)
  {
   for(int i = 0;i<10;i++)
   	if(obj->alarm[i]>0)
   {
    obj->alarm[i]--;
    if(obj->alarm[i]<=0)
    	obj->event_alarm(i);
   }
  }
  
  //运动
  //printf("room step run\n");
  for(object*obj:object::all_object)
  {
   int x,y;
   toSpin(obj->x,obj->y,obj->speed,
    obj->speed,obj->direction,&x,&y);
   obj->x = x;
   obj->y = y;
  }
  
  //步事件
  //printf("room step step\n");
  for(object*obj:object::all_object)
  {
   obj->event_step();
  }
  
  //动画
  //printf("room step image\n");
  for(object*obj:object::all_object)
  {
   if(obj->sprite_index==NULL)
   	continue;
   
   obj->image_index+=
   obj->image_speed;
   obj->image_index = obj->image_index
   -(int)obj->image_index
   +(int)obj->image_index
   %obj->sprite_index->number;
  }
  
  //背景
  drawRect(0,0,SCRW,SCRH,
   background);
  
  //绘制
  object::all_object.sort
  (obj_depth_sort());
  for(object*obj:object::all_object)
  {
   //可见性判断
   if(!obj->visiable)
   	break;
   
   //视野控制
   obj->x-=view_pos_x;
   obj->y-=view_pos_y;
   obj->event_draw();
   obj->x+=view_pos_x;
   obj->y+=view_pos_y;
  }
  
  //运行fps
  char data[100];
  fps_run(game_fps);
  int fps = fps_get(game_fps);
  sprintf(data,(char*)"FPS:%d",fps);
  dtext(data,0,0,
   0xff,0xff,0xff,FALSE,0);
  ref(0,0,SCRW,SCRH);
  //printf("room%d step()\n",this);
 }
}

